import express from 'express';
import cors from 'cors';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// 添加计算年龄的辅助函数
const calculateAge = (birthDateString) => {
  const birthDate = new Date(birthDateString);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
};

// 转换患者对象，添加计算的年龄属性
const transformPatient = (patient) => {
  // 如果患者对象包含birthDate，则计算年龄
  if (patient.birthDate) {
    return {
      ...patient,
      age: calculateAge(patient.birthDate)
    };
  }
  return patient;
};

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 数据库配置
const DB_DIR = path.join(__dirname, 'db');
const PATIENTS_DB_PATH = path.join(DB_DIR, 'patients.json');
const IMAGES_DB_PATH = path.join(DB_DIR, 'images.json');
const REPORTS_DB_PATH = path.join(DB_DIR, 'aiReports.json');

// 确保数据库目录存在
if (!fs.existsSync(DB_DIR)) {
  fs.mkdirSync(DB_DIR, { recursive: true });
}

// 数据库管理类
class DatabaseManager {
  constructor() {
    // 确保数据库目录存在
    console.log('正在初始化数据库管理器，目录:', DB_DIR);
    if (!fs.existsSync(DB_DIR)) {
      try {
        fs.mkdirSync(DB_DIR, { recursive: true });
        console.log('数据库目录创建成功:', DB_DIR);
      } catch (error) {
        console.error('创建数据库目录失败:', error);
        throw new Error(`无法创建数据库目录: ${error.message}`);
      }
    } else {
      console.log('数据库目录已存在:', DB_DIR);
    }
    console.log('患者数据库文件路径:', PATIENTS_DB_PATH);
    console.log('图片数据库文件路径:', IMAGES_DB_PATH);
    console.log('报告数据库文件路径:', REPORTS_DB_PATH);
  }

  // 读取JSON文件
  readJsonFile(filePath, defaultValue = null) {
    try {
      console.log(`正在读取文件: ${filePath}`);
      if (fs.existsSync(filePath)) {
        console.log(`文件存在，正在读取: ${filePath}`);
        const data = fs.readFileSync(filePath, 'utf8');
        const parsedData = JSON.parse(data);
        console.log(`成功读取文件: ${filePath}, 数据长度: ${Array.isArray(parsedData) ? parsedData.length : '对象'}`);
        return parsedData;
      } else {
        console.log(`文件不存在: ${filePath}, 返回默认值`);
        // 如果提供了默认值，尝试写入文件
        if (defaultValue !== null) {
          console.log(`尝试写入默认值到文件: ${filePath}`);
          this.writeJsonFile(filePath, defaultValue);
        }
      }
    } catch (error) {
      console.error(`读取文件 ${filePath} 失败:`, error);
    }
    return defaultValue;
  }

  // 写入JSON文件数据
  writeJsonFile(filePath, data) {
    try {
      console.log(`正在写入文件: ${filePath}, 数据长度: ${Array.isArray(data) ? data.length : '对象'}`);
      // 确保目录存在
      const dir = path.dirname(filePath);
      if (!fs.existsSync(dir)) {
        console.log(`创建目录: ${dir}`);
        fs.mkdirSync(dir, { recursive: true });
      }
      // 使用UTF8编码写入，确保中文正确显示
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
      console.log(`成功写入文件: ${filePath}`);
      return true;
    } catch (error) {
      console.error(`写入文件 ${filePath} 失败:`, error);
      return false;
    }
  }

  // 获取患者列表
  getPatients() {
    console.log('获取患者列表');
    const patients = this.readJsonFile(PATIENTS_DB_PATH, []);
    console.log(`当前患者数据量: ${patients.length}`);
    // 如果数据库为空，初始化患者数据并保存
    if (patients.length === 0) {
      console.log('患者数据为空，初始化默认数据');
      const initialPatients = this.getInitialPatients();
      console.log('初始患者数据:', initialPatients);
      const saved = this.savePatients(initialPatients);
      console.log(`保存初始患者数据: ${saved ? '成功' : '失败'}`);
      return initialPatients;
    }
    return patients;
  }

  // 保存患者数据
  savePatients(patients) {
    return this.writeJsonFile(PATIENTS_DB_PATH, patients);
  }

  // 获取患者（根据ID）
  getPatientById(id) {
    const patients = this.getPatients();
    return patients.find(p => p.id === id);
  }

  // 关键字搜索患者（ID或姓名模糊）
  searchPatients(keyword) {
    const patients = this.getPatients();
    const kw = String(keyword || '').trim().toLowerCase();
    if (!kw) return patients;
    const num = parseInt(kw);
    const isNum = !isNaN(num);
    return patients.filter(p => {
      const idStr = String(p.id || '');
      const nameLower = String(p.name || '').toLowerCase();
      return (isNum && p.id === num) || idStr.includes(kw) || nameLower.includes(kw);
    });
  }

  // 添加患者
  addPatient(patient) {
    const patients = this.getPatients();
    // 生成新ID
    const newId = patients.length > 0 ? Math.max(...patients.map(p => p.id)) + 1 : 1;
    const newPatient = { ...patient, id: newId };
    patients.push(newPatient);
    if (this.savePatients(patients)) {
      return newPatient;
    }
    return null;
  }

  // 读取图片数据
  getImages() {
    return this.readJsonFile(IMAGES_DB_PATH, []);
  }

  // 保存图片数据
  saveImages(images) {
    return this.writeJsonFile(IMAGES_DB_PATH, images);
  }

  // 读取AI报告数据
  getAiReports() {
    return this.readJsonFile(REPORTS_DB_PATH, []);
  }

  // 保存AI报告数据
  saveAiReports(reports) {
    return this.writeJsonFile(REPORTS_DB_PATH, reports);
  }

  // 获取初始患者数据
  getInitialPatients() {
    // 使用明确的中文字符串
    return [
      { id: 1, name: '张三', gender: '男', birthDate: '1989-05-15' },
      { id: 2, name: '李四', gender: '女', birthDate: '1982-08-22' },
      { id: 3, name: '王五', gender: '男', birthDate: '1968-12-10' },
      { id: 4, name: '赵六', gender: '女', birthDate: '1995-03-07' },
      { id: 5, name: '钱七', gender: '男', birthDate: '1976-09-30' }
    ];
  }
}

const dbManager = new DatabaseManager();
const app = express();
const PORT = 3001;

// 中间件
app.use(cors());
app.use(express.json());

// 确保上传目录存在
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 获取所有患者
app.get('/api/patients', (req, res) => {
  try {
    // 从数据库读取患者数据
    const patients = dbManager.getPatients();
    // 转换每个患者对象，添加计算的年龄
    const patientsWithAge = patients.map(transformPatient);
    res.json(patientsWithAge);
  } catch (error) {
    console.error('获取患者列表失败:', error);
    res.status(500).json({ error: '获取患者列表失败' });
  }
});

// 搜索患者（按关键字）
app.get('/api/patients/search', (req, res) => {
  try {
    const q = req.query.q || '';
    const list = dbManager.searchPatients(q).map(transformPatient);
    res.json(list);
  } catch (error) {
    console.error('搜索患者失败:', error);
    res.status(500).json({ error: '搜索患者失败' });
  }
});

// 根据ID获取患者
app.get('/api/patients/:id', (req, res) => {
  try {
    const patientId = parseInt(req.params.id);
    const patient = dbManager.getPatientById(patientId);
    if (patient) {
      // 转换患者对象，添加计算的年龄
      res.json(transformPatient(patient));
    } else {
      res.status(404).json({ error: '患者未找到' });
    }
  } catch (error) {
    console.error('获取患者信息失败:', error);
    res.status(500).json({ error: '获取患者信息失败' });
  }
});

// 添加新患者
app.post('/api/patients', (req, res) => {
  try {
    // 确保必要字段存在
    if (!req.body.name || !req.body.gender || !req.body.birthDate) {
      return res.status(400).json({ error: '缺少必要的患者信息（姓名、性别、生日）' });
    }
    
    const patientData = {
      name: req.body.name,
      gender: req.body.gender,
      birthDate: req.body.birthDate
    };
    
    const newPatient = dbManager.addPatient(patientData);
    if (newPatient) {
      res.status(201).json(transformPatient(newPatient));
    } else {
      res.status(500).json({ error: '保存患者信息失败' });
    }
  } catch (error) {
    console.error('添加患者失败:', error);
    res.status(500).json({ error: '添加患者失败' });
  }
});

// 图片上传
app.post('/api/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No file uploaded' });
  }
  
  const currentImages = dbManager.getImages();
  const imageRecord = {
    id: currentImages.length + 1,
    filename: req.file.filename,
    originalname: req.file.originalname,
    path: req.file.path,
    size: req.file.size,
    mimetype: req.file.mimetype,
    patientId: Number(req.body.patientId),
    doctorId: req.body.doctorId ? Number(req.body.doctorId) : null,
    uploadTime: new Date().toISOString()
  };
  
  // 保存图片记录到数据库
  currentImages.push(imageRecord);
  dbManager.saveImages(currentImages);
  
  // 模拟AI分析
  setTimeout(() => {
    const currentReports = dbManager.getAiReports();
    const aiReport = {
      id: currentReports.length + 1,
      imageId: imageRecord.id,
      patientId: imageRecord.patientId,
      doctorId: imageRecord.doctorId,
      analysisResult: '正常',
      confidence: 0.95,
      details: '肺部影像未见明显异常',
      analysisTime: new Date().toISOString(),
      reviewStatus: '待复核', // 初始状态为待复核
      doctorComment: '',
      reportGenerated: false, // 标识是否已生成最终报告
      finalReport: null // 最终诊断报告内容
    };
    currentReports.push(aiReport);
    dbManager.saveAiReports(currentReports);
  }, 2000);
  
  res.status(201).json(imageRecord);
});

// 获取图片列表
app.get('/api/images', (req, res) => {
  try {
    const images = dbManager.getImages();
    res.json(images);
  } catch (error) {
    console.error('获取图片列表失败:', error);
    res.status(500).json({ error: '获取图片列表失败' });
  }
});

// 按患者ID获取图片
app.get('/api/images/patient/:patientId', (req, res) => {
  try {
    const patientId = parseInt(req.params.patientId);
    const images = dbManager.getImages().filter(img => Number(img.patientId) === patientId);
    res.json(images);
  } catch (error) {
    console.error('按患者获取图片失败:', error);
    res.status(500).json({ error: '按患者获取图片失败' });
  }
});

// 按医生获取图片
app.get('/api/images/doctor/:doctorId', (req, res) => {
  try {
    const doctorId = parseInt(req.params.doctorId);
    const images = dbManager.getImages().filter(img => Number(img.doctorId) === doctorId);
    res.json(images);
  } catch (error) {
    console.error('按医生获取图片失败:', error);
    res.status(500).json({ error: '按医生获取图片失败' });
  }
});

// 获取AI分析报告
app.get('/api/ai-reports', (req, res) => {
  try {
    const reports = dbManager.getAiReports();
    const patients = dbManager.getPatients();
    const images = dbManager.getImages();
    const enriched = reports.map(r => {
      const p = patients.find(x => x.id === r.patientId);
      const img = images.find(x => x.id === r.imageId);
      return {
        ...r,
        patientName: p ? p.name : '',
        imageFilename: img ? img.filename : ''
      };
    });
    res.json(enriched);
  } catch (error) {
    console.error('获取AI报告失败:', error);
    res.status(500).json({ error: '获取AI报告失败' });
  }
});

// 获取指定患者的报告（富化）
app.get('/api/ai-reports/patient/:patientId', (req, res) => {
  try {
    const patientId = parseInt(req.params.patientId);
    const reports = dbManager.getAiReports().filter(report => report.patientId === patientId);
    const patients = dbManager.getPatients();
    const images = dbManager.getImages();
    const enriched = reports.map(r => {
      const p = patients.find(x => x.id === r.patientId);
      const img = images.find(x => x.id === r.imageId);
      return {
        ...r,
        patientName: p ? p.name : '',
        imageFilename: img ? img.filename : ''
      };
    });
    res.json(enriched);
  } catch (error) {
    console.error('获取患者报告失败:', error);
    res.status(500).json({ error: '获取患者报告失败' });
  }
});

// 获取指定医生的报告（富化）
app.get('/api/ai-reports/doctor/:doctorId', (req, res) => {
  try {
    const doctorId = parseInt(req.params.doctorId);
    const reports = dbManager.getAiReports().filter(report => Number(report.doctorId) === doctorId);
    const patients = dbManager.getPatients();
    const images = dbManager.getImages();
    const enriched = reports.map(r => {
      const p = patients.find(x => x.id === r.patientId);
      const img = images.find(x => x.id === r.imageId);
      return {
        ...r,
        patientName: p ? p.name : '',
        imageFilename: img ? img.filename : ''
      };
    });
    res.json(enriched);
  } catch (error) {
    console.error('按医生获取报告失败:', error);
    res.status(500).json({ error: '按医生获取报告失败' });
  }
});

// 医生复核API
app.post('/api/ai-reports/:reportId/review', (req, res) => {
  try {
    const reportId = parseInt(req.params.reportId);
    const { doctorComment, approved } = req.body;
    
    if (!doctorComment || typeof approved !== 'boolean') {
      return res.status(400).json({ error: '缺少必要的复核信息' });
    }
    
    const currentReports = dbManager.getAiReports();
    const reportIndex = currentReports.findIndex(r => r.id === reportId);
    
    if (reportIndex === -1) {
      return res.status(404).json({ error: '报告未找到' });
    }
    
    // 更新报告状态
    currentReports[reportIndex] = {
      ...currentReports[reportIndex],
      reviewStatus: '已复核',
      doctorComment: doctorComment,
      reviewTime: new Date().toISOString()
    };
    
    // 只有在医生同意（approved=true）后才生成最终诊断报告
    if (approved) {
      currentReports[reportIndex].reportGenerated = true;
      currentReports[reportIndex].finalReport = {
        id: `R-${Date.now()}`,
        generatedTime: new Date().toISOString(),
        content: `基于AI分析和医生复核，患者的诊断结果为：${currentReports[reportIndex].analysisResult}。医生意见：${doctorComment}`,
        status: '已完成'
      };
    }
    
    dbManager.saveAiReports(currentReports);
    res.json(currentReports[reportIndex]);
  } catch (error) {
    console.error('医生复核失败:', error);
    res.status(500).json({ error: '医生复核失败' });
  }
});

// 获取指定报告
app.get('/api/ai-reports/:reportId', (req, res) => {
  try {
    const reportId = parseInt(req.params.reportId);
    const report = dbManager.getAiReports().find(r => r.id === reportId);
    
    if (!report) {
      return res.status(404).json({ error: '报告未找到' });
    }
    
    const patient = dbManager.getPatients().find(p => p.id === report.patientId);
    const image = dbManager.getImages().find(img => img.id === report.imageId);
    
    const enrichedReport = {
      ...report,
      patientName: patient ? patient.name : '',
      imageFilename: image ? image.filename : ''
    };
    
    res.json(enrichedReport);
  } catch (error) {
    console.error('获取报告详情失败:', error);
    res.status(500).json({ error: '获取报告详情失败' });
  }
});

// 提供上传的图片访问
app.use('/uploads', express.static(uploadDir));

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});